<template>
	<view>
		<span>
			{{ formattedTime }}
		</span>
	</view>
</template>

<script>
	export default {
		props: {
			endTime: {
				type: Number,
				required: true
			}
		},
		data() {
			return {
				countdown: 0
			}
		},
		computed: {
			formattedTime() {
				const mins = Math.floor(this.countdown / 60);
				const secs = this.countdown % 60;
				if(this.countdown == 0){
					return `订单已取消`;
				}else{
					return `订单将在${mins}:${secs < 10 ? '0' : ''}${secs}后取消`;
				}
			},
		},
		methods: {
			// 计算剩余时间（毫秒）
			calculateCountdown() {
				const now = Date.now();
				const endTime = this.endTime // 15分钟超时
				this.countdown = Math.max(0, Math.floor((endTime - now) / 1000));
			},

			// 启动定时器
			startTimer() {
				this.timer = setInterval(() => {
					if (this.countdown > 0) {
						this.countdown--;
					} else {
						this.clearTimer();
						this.$emit('timeout'); // 触发超时事件
					}
				}, 1000);
			},

			// 清除定时器
			clearTimer() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			}
		},
		mounted() {
			this.calculateCountdown(); // 初始化倒计时
			this.startTimer(); // 启动定时器 
		},
		beforeDestroy() {
			this.clearTimer(); // 组件销毁时清除定时器
		}
	}
</script>